<script setup lang="ts">
import {ref, reactive, PropType} from 'vue'
import {ElMessage, FormRules} from 'element-plus'
import {RoleFormInfor, saveRoleInfor} from '@/api/baseSetting/roleManager'
import dDialog from '@/components/dDialog/dDialog.vue'
import dFrom from '@/components/dFrom/dFrom.vue'
import {ChineseAlphanumeric, Normal} from '@/util/common'
import {FromItem} from '@/components/dFrom/dFrom'

type DialogType = 'add' | 'edit'

//是否显示
const props = defineProps({
  //显示
  showDialog: {
    type: Boolean,
    required: true
  },
  //弹窗类型
  dialogType: {
    type: String as PropType<DialogType>,
    required: true
  },
  //数据
  roleData: {
    type: Object as PropType<RoleFormInfor>,
    required: true
  }
})

const resetFieldsFlag = ref(false)
const validateFlag = ref(false)

const emits = defineEmits(['close'])

const fromItems = ref<Array<FromItem>>([
  {
    label: '角色名称',
    prop: 'roleName',
    placeholder: '请输入角色名称',
    type: 'input'
  },
  {
    label: '角色说明',
    prop: 'remark',
    placeholder: '请输入角色说明',
    type: 'input',
    inputType: 'textarea'
  }
])

//信息
const fromData: RoleFormInfor = reactive(props.roleData)

const rules = reactive<FormRules>({
  roleName: [
    {
      required: true,
      message: '只能输入汉字、字母、数字',
      pattern: ChineseAlphanumeric,
      trigger: ['change', 'blur']
    },
    {
      required: true,
      message: '长度应不超过20个字符',
      trigger: ['change', 'blur'],
      max: 20
    }
  ],
  remark: [
    {
      required: false,
      message: '只能输入汉字、字母、数字、字符',
      pattern: Normal,
      trigger: ['change', 'blur']
    },
    {
      required: false,
      message: '长度应不超过100个字符',
      trigger: ['change', 'blur'],
      max: 100
    }
  ]
})

const showSaveLoading = ref(false)

const onClose = () => {
  emits('close')
  //关闭后清除表单数据以及表单验证数据 可根据具体业务自行调整
  resetFieldsFlag.value = !resetFieldsFlag.value
}

const onCancel = () => {
  onClose()
}

//表单验证通过事件
const onSubmit = () => {
  showSaveLoading.value = true
  fromData.remark = fromData.remark || ''
  saveRoleInfor(fromData)
    .then(() => {
      ElMessage.success('保存成功')
      emits('close')
    })
    .finally(() => {
      showSaveLoading.value = false
    })
}

const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}
</script>

<template>
  <d-dialog
    :title="props.dialogType === 'edit' ? '编辑角色' : '新增角色'"
    :show-dialog="showDialog"
    :show-save-loading="showSaveLoading"
    :width="600"
    @cancel="onCancel"
    @confirm="onConfirm"
    @close="onClose"
  >
    <d-from
      label-position="right"
      class="d-form-input-w-2"
      :label-width="120"
      :reset-fields-flag="resetFieldsFlag"
      :validate-flag="validateFlag"
      :rules="rules"
      :form-line-num="1"
      :form-data="fromData"
      :form-items="fromItems"
      @submit="onSubmit"
    />
  </d-dialog>
</template>

<style scoped></style>
